package com.zmn.oms.zmn.aop;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.amount.AmountUtil;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.constant.MessageQueueTagConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.OmsBaseOperator;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.dto.OmsStatusOperator;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.zmn.FactoryBatchNewOrderDIO;
import com.zmn.oms.model.dto.order.zmn.FinalPriceNewOrderExtDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotation;
import com.zmn.oms.model.entity.post.OrderPost;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.third.dj58.DaoJia58Consts;
import com.zmn.oms.third.tc58.Tc58Consts;
import com.zmn.oms.third.zhimi.ZhimiConsts;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 类描述:
 *
 * @author liuying
 * @date 2019/01/05 10:38 AM
 */
public class OrderWorkLogUtils {

    /**
     * 保险单处理的操作类型：领单（非家修匠订单）、上门（家修匠订单）、多工程师、完成、取消
     */
    public static List<Integer> INS_OP_TYPE_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_TAKE,
            OrderLogConsts.ORDER_LOG_TYPE_VISIT,
            OrderLogConsts.ORDER_LOG_TYPE_MULTI_MASTER,
            OrderLogConsts.ORDER_LOG_TYPE_CANCEL,
            OrderLogConsts.ORDER_LOG_TYPE_COMPLETE);

    /**
     * 订单同步操作类型：
     */
    public static List<Integer> SYNC_ORDER_OP_TYPE_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_INPUT,
            OrderLogConsts.ORDER_LOG_TYPE_UPDATE,
            OrderLogConsts.ORDER_LOG_TYPE_CONFIRM,
            OrderLogConsts.ORDER_LOG_TYPE_DISTRIBUTE,
            OrderLogConsts.ORDER_LOG_TYPE_TAKE,
            OrderLogConsts.ORDER_LOG_TYPE_VISIT,
            OrderLogConsts.ORDER_LOG_TYPE_COMPLETE,
            OrderLogConsts.ORDER_LOG_TYPE_SERVICE_COMPLETE,
            OrderLogConsts.ORDER_LOG_TYPE_CANCEL,
            // 工程师填价格
            OrderLogConsts.ORDER_LOG_TYPE_MASTER_CHANGE_PRICE,
            // 工程师改预约时间
            OrderLogConsts.ORDER_LOG_TYPE_MASTER_MODIFY_DUTY_TIME,
            // 修改预约时间
            OrderLogConsts.ORDER_LOG_TYPE_MODIFY_DUTY_TIME,
            // 挂起
            OrderLogConsts.ORDER_LOG_TYPE_ORDER_SUSPEND,
            // 更改服务项
            OrderLogConsts.ORDER_LOG_TYPE_SERVICEITEM,
            // 渠道收款
            OrderLogConsts.ORDER_LOG_TYPE_CHANNEL_PAY,
            // 改渠道预收
            OrderLogConsts.ORDER_LOG_TYPE_UPDATE_CHANNEL_PREPAY_AMOUNT,
            // 改预付款
            OrderConsts.ORDER_OP_TYPE_UPDATE_CHANNEL_PREPAY_AMOUNT,
//            // 总部预付
//            OrderConsts.ORDER_OP_TYPE_ADMIN_UPDATE_CHANNEL_PREPAY_AMOUNT,
            // 后台人工优惠
            OrderLogConsts.ORDER_LOG_TYPE_DISCOUNT_ARTIFICIAL_OPERATOR,
            // 工程师人工优惠
            OrderLogConsts.ORDER_LOG_TYPE_DISCOUNT_ARTIFICIAL_MASTER,
            // 优惠 六折
            OrderConsts.ORDER_OP_TYPE_DISCOUNT_LEVEL_ONE ,
//            // 优惠 七折
//            OrderConsts.ORDER_OP_TYPE_DISCOUNT_LEVEL_TWO ,
//            // 优惠 九折
//            OrderConsts.ORDER_OP_TYPE_DISCOUNT_LEVEL_THREE,
            // 优惠 全免
            OrderConsts.ORDER_OP_TYPE_DISCOUNT_FREE
    );

    /**
     * 厂商渠道同步操作类型：
     */
    public static List<Integer> SYNC_ORDER_OP_TYPE_FACTORY_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_FACTORY_REMARK
    );

    /**
     * 订单同步操作类型：
     */
    public static List<Integer> SYNC_ORDER_OP_ADD_UPDATE_TYPE_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_INPUT,
            OrderLogConsts.ORDER_LOG_TYPE_UPDATE,
            OrderLogConsts.ORDER_LOG_TYPE_CONFIRM
    );

    /**
     * 订单同步新单类型
     */
    public static List<Integer> SYNC_ORDER_NEW_TYPE_LIST = Lists.newArrayList(
            OrderConsts.ORDER_INPUT_TYPE_SYNC_MANUAL_ALL,
            OrderConsts.ORDER_INPUT_TYPE_SYNC_MANUAL_NEW,
            OrderConsts.ORDER_INPUT_TYPE_SYNC_H5_ALL,
            OrderConsts.ORDER_INPUT_TYPE_SYNC_H5_NEW
    );

    /**
     * 需要同步新单（后台录入的新单）的渠道
     */
    public static List<Integer> SYNC_ORDER_NEW_CHANNEL_LIST = Lists.newArrayList(
            OrderConsts.CHANNEL_ID_GUANGZHOU_HAOBAI_WECHAT,
            OrderConsts.CHANNEL_ID_DJ58_DAG, // 需要回复接单
            OrderConsts.CHANNEL_ID_BAIDU_APP, // 百度小程序，需要同步新单录入
            DaoJia58Consts.CHANNEL_ID_API,  // 58到家-直约API：需要回复接受订单
            DaoJia58Consts.CHANNEL_ID_APARTMENT,  // 58到家-同城公寓：需要回复接受订单
            OrderConsts.CHANNEL_ID_JD_HUADI,  // 需要回复接单
            ZhimiConsts.CHANNEL_ID,  // 需要回复订单确认收到
            Tc58Consts.CHANNEL_ID_VIP, // 需要回复订单确认收到
            Tc58Consts.CHANNEL_ID_FWK, // 需要回复订单确认收到
            Tc58Consts.CHANNEL_ID_JX, // 需要回复订单确认收到
            Tc58Consts.CHANNEL_ID_JX_PIPE, // 需要回复订单确认收到
            Tc58Consts.CHANNEL_ID_JX_CLOCK // 需要回复订单确认收到
    );

    /**
     * 订单同步状态变更类型
     */
    public static List<Integer> SYNC_ORDER_CHANGE_TYPE_LIST = Lists.newArrayList(
            OrderConsts.ORDER_INPUT_TYPE_SYNC_MANUAL_ALL,
            OrderConsts.ORDER_INPUT_TYPE_SYNC_H5_ALL,
            OrderConsts.ORDER_INPUT_TYPE_API
    );


    /**
     * 订单同步状态变更类型
     */
    public static List<Integer> SYNC_FICO_ORDER_REDUNDANCE_CHANGE_TYPE_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_COMPLETE,
            OrderLogConsts.ORDER_LOG_TYPE_CHECKOUT,
            OrderLogConsts.ORDER_LOG_TYPE_ACCOUNT
    );

    /**
     * 同步到呼叫的操作
     */
    public static List<Integer> SYNC_CALL_ORDER_TYPE_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_INPUT,
            OrderLogConsts.ORDER_LOG_TYPE_TURN,
            OrderLogConsts.ORDER_LOG_TYPE_ASSIGN
    );

    /**
     * 改派申请取消需要处理的操作
     */
    public static List<Integer> REDISTRIBUTE_APPLY_CANCEL_TYPE_LIST = Lists.newArrayList(
            OrderLogConsts.ORDER_LOG_TYPE_CANCEL,
            OrderLogConsts.ORDER_LOG_TYPE_TURN,
            OrderLogConsts.ORDER_LOG_TYPE_ASSIGN,
            OrderLogConsts.ORDER_LOG_TYPE_ASSIGN_BACK,
            OrderLogConsts.ORDER_LOG_TYPE_DISTRIBUTE,
            OrderLogConsts.ORDER_LOG_TYPE_DISTRIBUTE_BACK,
            OrderLogConsts.ORDER_LOG_TYPE_COMPLETE
    );

    /**
     * 节点公共订阅
     */
    public static Map<Integer, String> SYNC_ORDER_NODE_MAP = new HashMap<Integer, String>() {
        {
            put(OrderLogConsts.ORDER_LOG_TYPE_INPUT, MessageQueueTagConsts.ORDER_ADD);
            put(OrderLogConsts.ORDER_LOG_TYPE_CONFIRM, MessageQueueTagConsts.ORDER_CONFIRM);
            put(OrderLogConsts.ORDER_LOG_TYPE_TURN, MessageQueueTagConsts.ORDER_TURN);
            put(OrderLogConsts.ORDER_LOG_TYPE_UPDATE_ADDRESS, MessageQueueTagConsts.ORDER_UPDATE_ADDRESS);
			put(OrderLogConsts.ORDER_LOG_TYPE_REFUND, MessageQueueTagConsts.ORDER_ADD);
			put(OrderLogConsts.ORDER_LOG_TYPE_COMPENSATE, MessageQueueTagConsts.ORDER_ADD);
			put(OrderLogConsts.ORDER_LOG_TYPE_UPDATE, MessageQueueTagConsts.ORDER_UPDATE_PHONE);
			put(OrderLogConsts.ORDER_LOG_TYPE_MASTER_MODIFY_DUTY_TIME, MessageQueueTagConsts.ORDER_UPDATE_DUTYTIME);
            put(OrderLogConsts.ORDER_LOG_TYPE_ASSIGN, MessageQueueTagConsts.ORDER_ASSIGN);
            put(OrderLogConsts.ORDER_LOG_TYPE_DISTRIBUTE, MessageQueueTagConsts.ORDER_DISTRIBUTE);
			put(OrderLogConsts.ORDER_LOG_TYPE_VISIT, MessageQueueTagConsts.ORDER_VISIT);
            put(OrderLogConsts.ORDER_LOG_TYPE_SERVICE_COMPLETE, MessageQueueTagConsts.ORDER_SERVICE_COMPLETE);
            put(OrderLogConsts.ORDER_LOG_TYPE_COMPLETE, MessageQueueTagConsts.ORDER_COMPLETE);
			put(OrderLogConsts.ORDER_LOG_TYPE_CANCEL, MessageQueueTagConsts.ORDER_CANCEL);
            put(OrderLogConsts.ORDER_LOG_TYPE_WARRANTY, MessageQueueTagConsts.ORDER_GEN_WARRANTY);
            put(OrderLogConsts.ORDER_LOG_TYPE_MASTER_LEAVE, MessageQueueTagConsts.ORDER_MASTER_LEAVE);
            put(OrderLogConsts.ORDER_LOG_TYPE_CONTACT_USER, MessageQueueTagConsts.ORDER_CONTACT_USER);
            put(OrderLogConsts.ORDER_LOG_TYPE_CHECKOUT, MessageQueueTagConsts.ORDER_CHECKOUT);
            put(OrderLogConsts.ORDER_LOG_TYPE_ACCOUNT, MessageQueueTagConsts.ORDER_ACCOUNT);
        }
    };

    /**
     * 处理订单log的操作
     *
     * @param orderLog 工单日志
     * @param operator 操作对象，允许为null，如果为null，则默认操作对象为系统
     */
    public static void processOrderLogOperater(OrderLog orderLog, OmsBaseOperator operator) {
        processOrderLogOperater(orderLog, operator, null);
    }

    /**
     * 处理订单log的操作
     *
     * @param orderLog 工单日志
     * @param operator 操作对象，允许为null，如果为null，则默认操作对象为系统
     */
    public static void processOrderLogOperater(OrderLog orderLog, OmsBaseOperator operator, OrderWork orderWork) {
        if (operator == null) {
            // 系统
            orderLog.setOperator("系统");
            orderLog.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            orderLog.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        } else {
            if (Objects.equals(operator.getOperatorType(), 0)) {
                operator.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
                operator.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            }
            int operatorType = Optional.ofNullable(operator.getOperatorType()).orElse(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            if (orderWork != null && Objects.equals(operator.getOperatorType(), GlobalConsts.OPERATE_USER_TYPE_MASTER)
                    && StringUtils.isBlank(operator.getOperator())) {
                operator.setOperator(orderWork.getMasterName());
            }
            orderLog.setOperator(Optional.ofNullable(operator.getOperator()).orElse(GlobalConsts.getOperatorTypeName(operatorType)));
            if (Objects.equals(GlobalConsts.OPERATE_USER_TYPE_USER, operatorType) && StringUtil.isMobile(operator.getOperator())) {
                orderLog.setOperator(StringUtil.formatHideMobile(operator.getOperator()));
            }
            orderLog.setOperatorId(Optional.ofNullable(operator.getOperatorId()).orElse((long)operatorType));
            orderLog.setOperatorType(operatorType);
            orderLog.setCreateTime(operator.getOperateTime());
        }
    }

    /**
     * 处理工单状态
     *
     * @param orderLog
     * @param operator
     * @return
     */
    public static OrderWork processOrderLogStatus(OrderLog orderLog, OrderWork dbOrderWork, OmsOperator operator) {

        // 订单Id 工单Id
        orderLog.setOrderId(operator.getOrderId());
        orderLog.setWorkId(operator.getWorkId());

        // 操作经纬度
        orderLog.setLatitude(operator.getLatitude());
        orderLog.setLongitude(operator.getLongitude());

        // 操作前状态结果
        Integer status = dbOrderWork.getStatus();
        Integer resultStatus = dbOrderWork.getResultStatus();

        // 退款单、赔偿单，处理
        if (Objects.equals(OrderLogConsts.ORDER_LOG_TYPE_REFUND, orderLog.getType()) || Objects.equals(OrderLogConsts.ORDER_LOG_TYPE_COMPENSATE, orderLog.getType())) {
            status = OrderStatusConsts.WORK_STATUS_INPUT;
            resultStatus = OrderStatusConsts.WORK_RESULT_DOING;
        }

        String orderStatusName = OrderStatusConsts.getWorkStatusName(status);
        String orderResultStatusName = OrderStatusConsts.getWorkResultStatusName(resultStatus);
        orderLog.setBeforeStatus(status);
        orderLog.setBeforeStatusName(orderStatusName);
        orderLog.setBeforeResultStatus(resultStatus);
        orderLog.setBeforeResultStatusName(orderResultStatusName);

        // 操作后状态结果
        if (operator instanceof OmsStatusOperator) {
            // 修改订单
            OmsStatusOperator omsStatusOperator = (OmsStatusOperator) operator;
            if (omsStatusOperator.getStatus() != null) {
                status = omsStatusOperator.getStatus();
                orderStatusName = OrderStatusConsts.getWorkStatusName(omsStatusOperator.getStatus());
            }
            if (omsStatusOperator.getResultStatus() != null) {
                resultStatus = omsStatusOperator.getResultStatus();
                orderResultStatusName = OrderStatusConsts.getWorkResultStatusName(omsStatusOperator.getResultStatus());
            }
        }

        orderLog.setAfterStatus(status);
        orderLog.setAfterStatusName(orderStatusName);
        orderLog.setAfterResultStatus(resultStatus);
        orderLog.setAfterResultStatusName(orderResultStatusName);

        return dbOrderWork;
    }

    /**
     * 状态变更同步
     *
     * @param orderLog
     * @return
     */
    public static boolean isOrderStatusChanged(OrderLog orderLog) {
        if (Objects.equals(orderLog.getAfterStatus(), orderLog.getBeforeStatus()) && Objects.equals(orderLog.getAfterResultStatus(), orderLog.getBeforeResultStatus())) {
            return false;
        }
        return true;
    }

    /**
     * 新单log
     *
     * @param orderBO
     * @param operator
     * @param orderLog
     * @modififier huangchao 2022/04/01 取消：工程师动态库存记录
     */
    public static void processNewOrderLog(OrderBO orderBO, OmsBaseOperator operator, OrderLog orderLog) {
        OrderWork orderWork = orderBO.getOrderWork();
        OrderDetail orderDetail = orderBO.getOrderDetail();
        List<OrderProduct> orderProducts = orderBO.getOrderProductList();
        // 订单Id 工单Id
        orderLog.setOrderId(orderWork.getOrderId());
        orderLog.setWorkId(orderWork.getWorkId());

        // 操作前状态结果
        String orderStatusName = OrderStatusConsts.getWorkStatusName(OrderStatusConsts.WORK_STATUS_INPUT);
        String orderResultStatusName = OrderStatusConsts.getWorkResultStatusName(OrderStatusConsts.WORK_RESULT_DOING);
        orderLog.setBeforeStatus(OrderStatusConsts.WORK_STATUS_INPUT);
        orderLog.setBeforeStatusName(orderStatusName);
        orderLog.setBeforeResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
        orderLog.setBeforeResultStatusName(orderResultStatusName);

        orderLog.setAfterStatus(orderWork.getStatus());
        orderLog.setAfterStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setAfterResultStatus(orderWork.getResultStatus());
        orderLog.setAfterResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));
        if (operator != null) {
            StringBuilder sb = new StringBuilder();
            if (operator instanceof FactoryBatchNewOrderDIO) {
                sb.append("【批量录入】").append("\n");
            }
            StringBuilder address = new StringBuilder();
            address.append("地址信息：");
            address.append(orderDetail.getProvinceName()).append(orderDetail.getCityName()).append(orderDetail.getCountyName())
                    .append(StringUtils.defaultString(orderDetail.getStreet())).append(StringUtils.defaultString(orderDetail.getAddress()))
                    .append("经纬度：").append(orderDetail.getLongitude()).append(",").append(orderDetail.getLatitude());
            sb.append(address);
            sb.append("\n");
            List<String> productListLog = Lists.newArrayList();
            sb.append("产品信息：");
            orderProducts.forEach(orderProduct->{
                String orderProductString = String.format("前台产品[%s]-后台产品[%s],数量:%s,品牌:%s", StringUtils.defaultIfBlank(orderProduct.getShowProductName(), "-"), StringUtils.defaultIfBlank(orderProduct.getProductName(), "-"),orderProduct.getNumber(), StringUtils.defaultIfBlank(orderProduct.getBrandName(), "-"));
                productListLog.add(orderProductString);
            });
            sb.append(StringUtils.join(productListLog, "；"));
            sb.append("\n");
            if (StringUtils.isNotBlank(operator.getOperatorRemark())) {
                sb.append(operator.getOperatorRemark()).append("\n");
            }
            if (StringUtils.isNotBlank(operator.getOperatorLogRemark())) {
                sb.append("；").append(operator.getOperatorLogRemark()).append("\n");
            }

            List<OrderPost> orderPostList = orderBO.getOrderPostList();
            if (CollectionUtils.isNotEmpty(orderPostList)) {
                sb.append("快递信息: ");
                orderPostList.forEach(orderpost -> {
                    sb.append(" 快递单号:").append(orderpost.getExpressCode());
                    sb.append(" 快递公司:").append(orderpost.getExpressCompany());
                    if (StringUtils.isNotBlank(orderpost.getRemark())) {
                        sb.append(" 快递备注:").append(orderpost.getRemark());
                    }
                });
                sb.append("\n");
            }
            if (operator instanceof ZsNormalNewOrderDTO) {
                ZsNormalNewOrderDTO zsNormalNewOrderDTO = (ZsNormalNewOrderDTO) operator;
//                NewOrderDistributeMasterDTO distributeMasterDTO = zsNormalNewOrderDTO.getDistributeMasterDTO();
//                if (Objects.nonNull(distributeMasterDTO) && StringUtil.isNotBlank(distributeMasterDTO.getDistributeMasterLog())) {
//                    sb.append("工程师动态库存：").append(distributeMasterDTO.getDistributeMasterLog());
//                    sb.append("\n");
//                }

                FinalPriceNewOrderExtDTO finalPriceNewOrderExtDTO = zsNormalNewOrderDTO.getFinalPriceNewOrderExtDTO();
                if (Objects.nonNull(finalPriceNewOrderExtDTO) && StringUtil.isNotBlank(finalPriceNewOrderExtDTO.getItemTypeName())) {
                    sb.append("服务项目类型：").append(finalPriceNewOrderExtDTO.getItemTypeName());
                    sb.append("\n");
                }
            }
            List<OrderFinalPriceQuotation> quotationList = orderBO.getQuotationList();
            if (CollectionUtil.isNotNullOrEmpty(quotationList)) {
                OrderFinalPriceQuotation quotation = quotationList.get(0);
                if (StringUtil.isNotBlank(quotation.getPhenName())) {
                    sb.append(" 故障现象:").append(quotation.getPhenName()).append("\n");
                }
                if (StringUtil.isNotBlank(quotation.getServItemName())) {
                    sb.append(" 服务项:").append(quotation.getServItemName()).append("\n");
                }
                if (StringUtil.isNotBlank(quotation.getCategName())) {
                    sb.append(" 产品类别:").append(quotation.getCategName()).append("\n");
                }
                if (StringUtil.isNotBlank(quotation.getTariffName())) {
                    sb.append(" 产品型号:").append(quotation.getTariffName()).append("\n");
                }
                if (NumberUtil.isNotNullOrZero(quotation.getTotalAmount())) {
                    sb.append(" 服务价格:").append(amount2String(quotation.getTotalAmount())).append("元");
                }
            }

            orderLog.setContent(sb.toString());
        }
    }
    /**
     * 分转为元字符串
     */
    static String amount2String(Integer amount) {
        if (amount == null) {
            return null;
        }

        double dAmount = AmountUtil.fen2Yuan(amount).doubleValue();
        return String.format("%.2f", dAmount);
    }
}
